﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Validation.sp2010.Classes;
using System.Globalization;
using System.Collections;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Validation.sp2010.Helper;

namespace Validation.sp2010.Layouts.Validation.sp2010
{
    public partial class FormTask : LayoutsPageBase
    {
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            this.MasterPageFile = SPContext.Current.Web.MasterUrl;

        }

        #region Event
        protected void Page_Load(object sender, EventArgs e)
        {


            if (IsPostBack)
                return;


            //get current Task

            SPListItem taskValidation = SPContext.Current.ListItem;
            SPWeb web = SPContext.Current.Web;

            //SetFieldTterator
            #region Update Field Iterator

            try
            {
                //set FieldIterator options
                SPList list = web.Lists[new Guid(taskValidation[SPBuiltInFieldId.WorkflowListId].ToString())];
                SPListItem item = list.GetItemById((int)taskValidation[SPBuiltInFieldId.WorkflowItemId]);

                ListFieldIterator.ItemId = item.ID;
                ListFieldIterator.ListId = list.ID;

                LabelCreatedBy.Text = string.Format(HelperUtilities.GetResources("label_createdBy", web.Language),
                    item[SPBuiltInFieldId.Created],
                    HelperUtilities.GetValueLookup(item[SPBuiltInFieldId.Author].ToString()),
                    item[SPBuiltInFieldId.Last_x0020_Modified],
                    HelperUtilities.GetValueLookup(item[SPBuiltInFieldId.Editor].ToString()));

            }
            catch (Exception)
            {
                //Current User cannot view List or ListItem
                ListFieldIterator.Visible = false;
                Error_Iterator.Visible = true;
            } 
            #endregion


            bool withExtension = bool.Parse(taskValidation[Constante.FieldGuid.WithExtention].ToString());
            bool forceValidation = bool.Parse(taskValidation[Constante.FieldGuid.ForceValidation].ToString());
            bool isEdit = this.Request.QueryString["mode"] == "Edit";
            bool ifUserHavePermission = taskValidation.DoesUserHavePermissions(SPBasePermissions.EditListItems);
            bool enableAttachement = taskValidation.ParentList.EnableAttachments;
            bool taskCompeted = taskValidation[SPBuiltInFieldId.TaskStatus].ToString() == SPResource.GetString(CultureInfo.GetCultureInfo((int)web.Language), "WorkflowTaskStatusComplete");

            #region Set value controls
            
            //Title & desc task
            Literal_TaskTitle.Text = taskValidation.Title;
            if (taskValidation[SPBuiltInFieldId.Body] != null)
                Literal_TaskDesc.Text = taskValidation[SPBuiltInFieldId.Body].ToString();
            // set comment value
            var valComment = taskValidation[Constante.FieldGuid.Comment];
            if (valComment != null)
                comment_TextBox.Text = valComment.ToString();

            //if the task contain next_validaor field, set the Peopde Editor value
            #region next Validator
            var val = taskValidation[Constante.FieldGuid.NextValidator];
            if (val != null)
            {
                SPFieldUser field = taskValidation.Fields[Constante.FieldGuid.NextValidator] as SPFieldUser;
                if (field != null)
                {
                    SPFieldUserValue fieldValue =
                     field.GetFieldValue(val.ToString()) as SPFieldUserValue;
                    if (fieldValue != null)
                    {
                        if (fieldValue.User != null)
                        {
                            ValidatorUser.CommaSeparatedAccounts = fieldValue.User.LoginName;
                        }
                        else
                        {
                            ValidatorUser.CommaSeparatedAccounts = fieldValue.LookupValue;
                        }
                    }
                }
            } 
            #endregion


            //attachement
            #region Attachement controls

            string url = SPContext.Current.Web.ServerRelativeUrl + string.Format("/_layouts/15/AttachFile.aspx?ListId={0}&ItemId={1}&Source={2}", SPContext.Current.ListId, taskValidation.ID,
            SPContext.Current.Web.ServerRelativeUrl + "/" + this.Request.Url.PathAndQuery);

            HiddenUrlAttachement.Value = url;


//            string finalurl = @"javascript:var options = {
//             url: '" + url + @"',
//             dialogReturnValueCallback: function (dialogResult) {
//                 if (dialogResult) {
//                     document.location.reload(true);
//                 }
//             }
//            };SP.UI.ModalDialog.showModalDialog(options);";

//            AttachementLink.HRef = finalurl;

            SPFolder attachementFolder = web.GetFolder(SPContext.Current.List.RootFolder.ServerRelativeUrl + "/Attachments/" + taskValidation.ID);
            if (attachementFolder.Exists)
            {
                List<AttachementFileModel> attachements = new List<AttachementFileModel>();
                foreach (SPFile file in attachementFolder.Files)
                {
                    attachements.Add(new AttachementFileModel()
                    {
                        Name = file.Name,
                        Id = taskValidation.ID,
                        Url = file.ServerRelativeUrl,
                        IdList = taskValidation.ParentList.ID.ToString(),
                        IsEdit =isEdit
                    });
                }

                ViewState[state_allfiles] = attachements;
                RepeaterAttachements.DataSource = attachements;
                RepeaterAttachements.DataBind();
            }
            #endregion


            #endregion

            #region Set Visibilty controls

            //buttons action visiblity
            EditButton.Visible = !isEdit && ifUserHavePermission;
            AttachementLink.Visible = isEdit && enableAttachement;

            //rows visible
            Row_nextValidator.Visible = withExtension;
            Row_Attachement.Visible=enableAttachement;

            
            //controls enables
            ValidatorUser.Enabled = isEdit;
            comment_TextBox.Enabled = isEdit;

            //buttons visiblity

            save.Visible = isEdit;
            validate.Visible = isEdit && !taskCompeted ;
            refuse.Visible = isEdit && !taskCompeted && !forceValidation;
            validateWith.Visible = isEdit && !taskCompeted && withExtension;

            #endregion

       
            ViewState[state_deleteFiles] = new List<string>();

        }

        #region Button actions
        protected void Save_Click(object sender, EventArgs e)
        {
            SPList CurrentListTask = SPContext.Current.List;
            SetResponse(null, false, false);
        }

        protected void Validate_Click(object sender, EventArgs e)
        {
            SPList CurrentListTask = SPContext.Current.List;
            SetResponse((CurrentListTask.Fields[Constante.FieldGuid.Response] as SPFieldChoice).Choices[1], true, false);
        }
        protected void Refuse_Click(object sender, EventArgs e)
        {
            SPList CurrentListTask = SPContext.Current.List;
            SetResponse((CurrentListTask.Fields[Constante.FieldGuid.Response] as SPFieldChoice).Choices[2], true, false);

        }

        protected void ValidateWith_Click(object sender, EventArgs e)
        {
            SPList CurrentListTask = SPContext.Current.List;
            SetResponse((CurrentListTask.Fields[Constante.FieldGuid.Response] as SPFieldChoice).Choices[0], true, true);

        }

        
        #endregion

        /// <summary>
        /// Edit Form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            SPListItem taskValidation = SPContext.Current.ListItem;

            if (SPContext.Current.IsPopUI)
            {
                Response.Redirect(taskValidation.ParentList.DefaultEditFormUrl + "?ID=" + taskValidation.ID + "&IsDlg=1", true);
            }
            else
            {
                Response.Redirect(taskValidation.ParentList.DefaultEditFormUrl + "?ID=" + taskValidation.ID, true);
            }
        }


        protected void Links_ItemCommand(Object Sender, RepeaterCommandEventArgs e)
        {
            //persist the deleted files attachements
            (ViewState[state_deleteFiles] as List<string>).Add(e.CommandArgument.ToString());

            //Bind the repeater
            List<AttachementFileModel> attachements = (ViewState[state_allfiles] as List<AttachementFileModel>);
            attachements.RemoveAt(e.Item.ItemIndex);

            RepeaterAttachements.DataSource = attachements;
            RepeaterAttachements.DataBind();
        }

        #endregion

        #region private method

        const string state_deleteFiles = "DeletedFile";
        const string state_allfiles = "AllFiles";


        private void SetResponse(string response, bool completed, bool validateWith)
        {
            SPListItem taskValidation = SPContext.Current.ListItem;
            SPWeb web = SPContext.Current.Web;

            Hashtable properties = new Hashtable();
            if (response != null)
                properties[Constante.FieldGuid.Response] = response;

            properties[Constante.FieldGuid.Comment] = comment_TextBox.Text;



            if (validateWith)
            {
                #region old
                //if (((PickerEntity)(ValidatorUser.Entities[0])).EntityType == "User")
                //{
                //    SPUser nextUser = web.AllUsers[ValidatorUser.Accounts[0].ToString()];
                //    SPFieldUserValue nexUserValue = new SPFieldUserValue(web, nextUser.ID, nextUser.Name);

                //    properties[Constante.FieldGuid.NextValidator] = nexUserValue;
                //}
                //else
                //{
                //    SPGroup nextGroup = web.SiteGroups[ValidatorUser.Accounts[0].ToString()];
                //    SPFieldUserValue nexUserValue = new SPFieldUserValue(web, nextGroup.ID, nextGroup.Name);

                //    properties[Constante.FieldGuid.NextValidator] = nexUserValue;
                //} 
                #endregion


                try
                {

                    SPUser nextUser = web.AllUsers[ValidatorUser.Accounts[0].ToString()];
                    SPFieldUserValue nexUserValue = new SPFieldUserValue(web, nextUser.ID, nextUser.Name);

                    properties[Constante.FieldGuid.NextValidator] = nexUserValue;

                }
                catch (Exception)
                {

                    SPGroup nextGroup = web.SiteGroups[ValidatorUser.Accounts[0].ToString()];
                    SPFieldUserValue nexUserValue = new SPFieldUserValue(web, nextGroup.ID, nextGroup.Name);

                    properties[Constante.FieldGuid.NextValidator] = nexUserValue;
                
                }

                



            }


            #region Complete task
            if (completed)
            {
                properties[SPBuiltInFieldId.TaskStatus] = SPResource.GetString(CultureInfo.GetCultureInfo((int)web.Language), "WorkflowTaskStatusComplete");
                properties[SPBuiltInFieldId.PercentComplete] = 1;
            }


            bool oldValueWeb = web.AllowUnsafeUpdates;
            web.AllowUnsafeUpdates = true;
            SPWorkflowTask.AlterTask(taskValidation, properties, false);
            web.AllowUnsafeUpdates = oldValueWeb;
            //if (completed)
            //{
            //    if ((int)taskValidation[SPBuiltInFieldId.WorkflowVersion] != 1)
            //    {
            //        taskValidation[SPBuiltInFieldId.WorkflowVersion] = 1;
            //        taskValidation.Update();
            //    }
            //}


            List<string> filesDeleted = (ViewState[state_deleteFiles] as List<string>);

            filesDeleted.ForEach(f =>
            {
                web.GetFile(f).Delete();
            });


            #endregion

            #region Close task

            if ((SPContext.Current != null) && SPContext.Current.IsPopUI)
            {

                this.Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
                this.Context.Response.Flush();
                this.Context.Response.End();
            }

            else
            {
                string source = this.Request.QueryString["Source"];
                if (!string.IsNullOrEmpty(source))
                {
                    this.Response.Redirect(source);
                }
                else
                    this.Response.Redirect(SPContext.Current.Web.Url);
            }
            #endregion
        }
        
        #endregion
       
    }

    [Serializable]
    public class AttachementFileModel
    {
        public string IdList {get;set;}
        public int Id { get; set; }
        public string Name { get; set; }
        public string Url { get; set; }
        public bool IsEdit { get; set; }
    }
}
